package com.jingyanzi.privilege.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jingyanzi.privilege.dao.SecurityBtnMapper;
import com.jingyanzi.privilege.dao.SecurityMenuMapper;
import com.jingyanzi.privilege.dao.SecurityRolebtnMapper;
import com.jingyanzi.privilege.domain.BtnDO;
import com.jingyanzi.privilege.domain.EmployeeDO;
import com.jingyanzi.privilege.domain.RoleDO;
import com.jingyanzi.privilege.domain.RoleUserDO;
import com.jingyanzi.privilege.domain.result.ResultDO;
import com.jingyanzi.privilege.domain.result.ResultSupport;
import com.jingyanzi.privilege.entity.SecurityBtn;
import com.jingyanzi.privilege.entity.SecurityBtnExample;
import com.jingyanzi.privilege.entity.SecurityBtnExample.Criteria;
import com.jingyanzi.privilege.entity.SecurityMenu;
import com.jingyanzi.privilege.entity.SecurityRolebtn;
import com.jingyanzi.privilege.entity.SecurityRolebtnExample;
import com.jingyanzi.privilege.query.BtnQueryDO;
import com.jingyanzi.privilege.service.IBtnService;
import com.jingyanzi.privilege.service.IEmployeeService;
import com.jingyanzi.privilege.util.BeanUtilsExtends;

/**
 * @author reagan
 * @Description:按钮实现类
 */
@Service("btnService")
public class BtnServiceImpl extends BaseServiceImpl implements IBtnService {
	/**
	 * 按钮数据库Mapper
	 */
	@Autowired
	private SecurityBtnMapper btnMapper;
	
	@Autowired
	private IEmployeeService employeeService;

	/**
	 * 角色按钮映射数据库Mapper
	 */
	@Autowired
	private SecurityRolebtnMapper rolebtnMapper;

	@Autowired
	private SecurityMenuMapper menuMapper;

	public ResultDO add(List<BtnDO> list) {
		ResultSupport result = new ResultSupport();
		for (BtnDO btnDO : list) {
			ResultDO res = add(btnDO);
			if (!res.isSuccess()) {
				result.setSuccess(false);
				return result;
			}
		}
		return result;
	}

	public ResultDO modifi(List<BtnDO> list) {
		ResultSupport result = new ResultSupport();
		for (BtnDO btnDO : list) {
			ResultDO res = modifi(btnDO);
			if (!res.isSuccess()) {
				result.setSuccess(false);
				return result;
			}
		}
		return result;
	}

	public ResultDO add(BtnDO btnDO) {

		SecurityBtn btn = new SecurityBtn();

		SecurityMenu menu = null;
		// 复制DO到Entity
		ResultSupport result = BeanUtilsExtends.copy(btn, btnDO);

		// 判断复制是否成功
		if (!result.isSuccess())
			return result;

		try {
			menu = menuMapper.selectByPrimaryKey(btnDO.getMenuId());
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.BTN_ADD_ERROR);
			result.setErrorMsg("获取菜单失败");
			result.setSuccess(false);
			return result;
		}
		// 设置时间、状态、删除标志
		btn.setCreatetime(Calendar.getInstance().getTime());
		btn.setStatus(1);
		btn.setIsDelete(1);
		btn.setMenuCode(menu.getCode());
		// 成功标志变量
		int r = -1;

		try {
			r = btnMapper.insertSelective(btn);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.BTN_ADD_ERROR);
			result.setErrorMsg("添加按钮失败");
			result.setSuccess(false);
			return result;
		}

		// 插入标志小于1时报错
		if (r < 1) {
			result.setErrorCode(ResultDO.BTN_ADD_ERROR);
			result.setErrorMsg("添加按钮失败");
			result.setSuccess(false);
			return result;
		}
		result.setModel(ResultDO.FIRST_MODEL_KEY, btn.getId());
		return result;
	}

	public ResultDO removeForMenuId(BtnQueryDO query) {

		ResultSupport result = new ResultSupport();

		SecurityBtnExample example = new SecurityBtnExample();
		// 按照菜单ID获取按钮
		example.createCriteria().andMenuIdEqualTo(query.getMenuId()).andIsDeleteEqualTo(1);

		int r = -1;
		// 获取结果
		List<SecurityBtn> list = null;
		try {
			list = btnMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.BTN_QUERY_ERROR);
			result.setErrorMsg("获取菜单对应按钮失败");
			result.setSuccess(false);
			return result;
		}

		if (list == null) {
			result.setErrorCode(ResultDO.BTN_QUERY_ERROR);
			result.setErrorMsg("获取菜单对应按钮失败");
			result.setSuccess(false);
			return result;
		}

		for (SecurityBtn btn : list) {
			try {
				// 删除对应的按钮
				r = removeMapping(btn.getId());
				if (r < -1)
					new Exception();
				btn.setMenuId(0);
				btn.setIsDelete(-1);
				r = btnMapper.updateByPrimaryKeySelective(btn);

			} catch (Exception e) {
				r = -1;
				result.setErrorCode(ResultDO.BTN_DELETE_ERROR);
				result.setErrorMsg("删除菜单对应按钮失败");
				result.setSuccess(false);
				return result;
			}
		}

		if (r < -1) {
			result.setErrorCode(ResultDO.BTN_DELETE_ERROR);
			result.setErrorMsg("删除菜单对应按钮失败");
			result.setSuccess(false);
			return result;
		}

		return result;
	}

	public ResultDO remove(Integer id) {

		ResultSupport result = new ResultSupport();

		SecurityBtn btn = new SecurityBtn();

		btn.setId(id);
		// 设置按钮的逻辑删除标志
		btn.setIsDelete(-1);

		int r = -1;
		// 删除关联关系方法
		r = removeMapping(id);

		if (r > -1) {
			try {
				r = -1;
				r = btnMapper.updateByPrimaryKeySelective(btn);
			} catch (Exception e) {
				result.setErrorCode(ResultDO.BTN_DELETE_ERROR);
				result.setErrorMsg("删除按钮失败");
				result.setSuccess(false);
				return result;
			}
		}

		if (r < 1) {
			result.setErrorCode(ResultDO.BTN_DELETE_ERROR);
			result.setErrorMsg("删除按钮失败");
			result.setSuccess(false);
			return result;
		}

		return result;
	}

	public ResultDO modifi(BtnDO btnDO) {

		SecurityBtn btn = new SecurityBtn();

		ResultSupport result = BeanUtilsExtends.copy(btn, btnDO);
		if (!result.isSuccess())
			return result;
		btn.setCreatetime(Calendar.getInstance().getTime());

		int r = -1;
		try {
			r = btnMapper.updateByPrimaryKeySelective(btn);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.BTN_EDIT_ERROR);
			result.setErrorMsg("修改按钮信息失败");
			result.setSuccess(false);
			return result;
		}
		if (r < 1) {
			result.setErrorCode(ResultDO.BTN_EDIT_ERROR);
			result.setErrorMsg("修改按钮信息失败");
			result.setSuccess(false);
			return result;
		}

		return result;
	}

	public ResultDO get(Integer id) {

		ResultSupport result = new ResultSupport();

		if (id < 1) {
			result.setSuccess(false);
			return result;
		}

		SecurityBtn btn = null;

		try {
			btn = btnMapper.selectByPrimaryKey(id);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.BTN_QUERY_ERROR);
			result.setErrorMsg("获取按钮信息失败");
			result.setSuccess(false);
			return result;
		}

		if (btn == null) {
			result.setErrorCode(ResultDO.BTN_QUERY_ERROR);
			result.setErrorMsg("获取按钮信息失败");
			result.setSuccess(false);
			return result;
		}

		result.setModel(ResultSupport.FIRST_MODEL_KEY, getBtnDO(btn));
		return result;
	}
	
	public ResultDO getRoleBtn(int userId) {
		
		ResultSupport result = new ResultSupport();
		
		ResultDO res = employeeService.getRole(userId);
		
		if(!res.isSuccess()) {
			result.setSuccess(false);
			return result;
		}
		
		List<RoleUserDO> roleUserDOList = (List<RoleUserDO>) res.getModel(ResultSupport.FIRST_MODEL_KEY);

		List<BtnDO> btnDOList = new ArrayList<BtnDO>();
		for(RoleUserDO roleUserDO : roleUserDOList) {
			SecurityRolebtnExample example = new SecurityRolebtnExample();
			example.createCriteria().andRoleidEqualTo(roleUserDO.getRoleId());
			List<SecurityRolebtn> list = null;
			try {
				list = rolebtnMapper.selectByExample(example);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			for (SecurityRolebtn roleBtn : list) {
				SecurityBtn btn = btnMapper.selectByPrimaryKey(roleBtn.getBtnid());
				if(btn != null) {
					BtnDO btnDO = new BtnDO();
					btnDO.setMenuCode(btn.getMenuCode());
					btnDO.setStatus(btn.getStatus());
					btnDO.setCode(btn.getCode());
					btnDOList.add(btnDO);
				}
			}
		}
		//return menuDOList.stream().sorted(Comparator.comparing(MenuDO::getSortNum)).collect(Collectors.toList());
		result.setModel(ResultSupport.FIRST_MODEL_KEY, btnDOList);

		return result;
	}
	
	public ResultDO queryForUserId(BtnQueryDO queryDO) {
		
		ResultSupport result = new ResultSupport();
		
		ResultDO res = employeeService.getRole(queryDO.getId());
		
		if(!res.isSuccess()) {
			result.setSuccess(false);
			return result;
		}
		
		List<RoleUserDO> roleUserDOList = (List<RoleUserDO>) res.getModel(ResultSupport.FIRST_MODEL_KEY);
		
		SecurityBtnExample example = new SecurityBtnExample();

		List<SecurityBtn> list = null;

		example.createCriteria().andMenuIdEqualTo(queryDO.getMenuId()).andIsDeleteEqualTo(1).andStatusEqualTo(1);
		
		try {
			list = btnMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.BTN_QUERY_ERROR);
			result.setErrorMsg("获取菜单对应按钮信息失败");
			result.setSuccess(false);
			return result;
		}
		
		List<BtnDO> btnDOList = new ArrayList<BtnDO>();
		for(RoleUserDO roleUserDO : roleUserDOList) {
		
		
			
			for(SecurityBtn btn : list) {
				SecurityRolebtnExample example1 = new SecurityRolebtnExample();
				// 以角色ID作为获取条件
				example1.createCriteria().andRoleidEqualTo(roleUserDO.getRoleId()).andBtnidEqualTo(btn.getId());
				int count = 0;
				count = rolebtnMapper.countByExample(example1);
				if(count > 0) {
					btnDOList.add(getBtnDO(btn));
				}
			}
		}
		
		result.setModel(ResultSupport.FIRST_MODEL_KEY, btnDOList);

		return result;
	}

	public ResultDO queryForRoleId(Integer roleId) {

		ResultSupport result = new ResultSupport();

		SecurityRolebtnExample example1 = new SecurityRolebtnExample();
		// 以角色ID作为获取条件
		example1.createCriteria().andRoleidEqualTo(roleId);

		List<SecurityRolebtn> list = null;
		try {
			list = rolebtnMapper.selectByExample(example1);
		} catch (Exception e) {
			result.setErrorCode(ResultDO.BTN_QUERY_ERROR);
			result.setErrorMsg("获取对应角色信息失败");
			result.setSuccess(false);
			return result;
		}
		List<BtnDO> btnDOList = new ArrayList<BtnDO>();

		for (SecurityRolebtn v : list) {
			try {
				SecurityBtn btn = btnMapper.selectByPrimaryKey(v.getBtnid());
				// 将角色对应的按钮放入按钮列表
				btnDOList.add(getBtnDO(btn));
			} catch (Exception e) {
				result.setErrorCode(ResultDO.BTN_ADD_ERROR);
				result.setErrorMsg("获取角色对应按钮信息失败");
				result.setSuccess(false);
				return result;
			}
		}

		result.setModel(ResultSupport.FIRST_MODEL_KEY, btnDOList);

		return result;
	}

	public ResultDO getMenuBtn(Integer menuId) {

		ResultSupport result = new ResultSupport();

		SecurityBtnExample example = new SecurityBtnExample();

		List<SecurityBtn> list = null;

		example.createCriteria().andMenuIdEqualTo(menuId).andIsDeleteEqualTo(1);

		try {
			list = btnMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.BTN_QUERY_ERROR);
			result.setErrorMsg("获取菜单对应按钮信息失败");
			result.setSuccess(false);
			return result;
		}

		result.setModel(ResultSupport.FIRST_MODEL_KEY, getBtnDOList(list));

		return result;

	}

	public ResultDO query(BtnQueryDO query) {

		ResultSupport result = new ResultSupport();

		List<SecurityBtn> list = null;

		SecurityBtnExample example = new SecurityBtnExample();

		Criteria createCriteria = example.createCriteria();

		// 按照菜单ID获取
		if (query.getMenuId() != 0) {
			createCriteria.andMenuIdEqualTo(query.getMenuId());
		}
		/*// 按照名字获取
		if (StringUtils.isNotBlank(query.getMenuCode())) {
			createCriteria.andMenuCodeEqualTo(getMenuCode);
		}
		*/
		// 按照菜单ID获取
		if (query.getStatus() != null) {
			createCriteria.andStatusEqualTo(query.getStatus());
		}

		// 删除标志
		createCriteria.andIsDeleteEqualTo(1);

		List<BtnDO> btnDOList = null;

		// 是否分页标志
		if (query.isPage()) {
			// 设置分页
			example.setLimitByPage(query.getStart() + "," + query.getPageRows());
			long count = btnMapper.countByExample(example);
			result.setModel(ResultSupport.SECOND_MODEL_KEY, count);
		}
		
		example.setOrderByClause("sortNum asc");

		try {
			list = btnMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.BTN_QUERY_ERROR);
			result.setErrorMsg("获取按钮信息失败");
			result.setSuccess(false);
			return result;
		}

		btnDOList = getBtnDOList(list);
		result.setModel(ResultSupport.FIRST_MODEL_KEY, btnDOList);

		return result;
	}

	private int removeMapping(int id) {

		int ret = -1;

		SecurityRolebtnExample example1 = new SecurityRolebtnExample();
		// 根据条件去查找要删除的关联关系
		example1.createCriteria().andBtnidEqualTo(id);

		try {
			ret = rolebtnMapper.deleteByExample(example1);
		} catch (Exception e) {
			ret = -1;
		}

		if (ret < 0) {
			return ret;
		}

		return 1;
	}
}
